#!/bin/bash

# Check if user is root
if [ $(id -u) != "0" ]; then
    printf "Error: You must be root to run this script!\n"
    exit 1
fi

printf "\n"
printf "==========================\n"
printf " MariaDB 10.0 Install	  \n"
printf "==========================\n"
printf "\n\n"

if [ ! -s websrc ]; then    
    printf "Error: directory websrc not found.\n"
    exit 1
fi

cd websrc

printf "\n========= source package download start =========\n\n"

if [ -s cmake-2.8.12.2.tar.gz ]; then
  echo "cmake-2.8.12.2.tar.gz [found]"
else
  echo "cmake-2.8.12.2.tar.gz download now..."
  wget http://www.cmake.org/files/v2.8/cmake-2.8.12.2.tar.gz
fi

if [ -s mariadb-10.0.10.tar.gz ]; then
  echo "mariadb-10.0.10.tar.gz [found]"
else
  echo "pmariadb-10.0.10.tar.gz download now..."
  wget http://download.nus.edu.sg/mirror/mariadb/mariadb-10.0.10/kvm-tarbake-jaunty-x86/mariadb-10.0.10.tar.gz
fi

mariadbMd5=`md5sum mariadb-10.0.10.tar.gz | awk '{print $1}'`
if [ "$mariadbMd5" != "14ce22b8197d4eae88d237776d47220f" ]; then
    echo "Error: mariadb-10.0.10.tar.gz package md5 value is invalid. Please check package download url";
    exit 1
fi

if [ -s cmake-2.8.12.2 ]; then
    rm -rf cmake-2.8.12.2 
fi
tar zxvf cmake-2.8.12.2.tar.gz

if [ -s mariadb-10.0.10 ]; then
    rm -rf mariadb-10.0.10
fi
tar zxvf mariadb-10.0.10.tar.gz

printf "\n========= source package download completed =========\n\n"

groupadd mysql
useradd -g mysql mysql -s /bin/false

mkdir -p /data/mysql
chown -R mysql:mysql /data/mysql

mkdir -p /usr/local/mysql

printf "========= Cmake install start... =========\n\n"

cd cmake-2.8.12.2
./configure --prefix=/usr/local
make
make install
cd -

printf "\n========= Cmake install end =========\n\n"
printf "========= MariaDB install start... =========\n\n"

cd mariadb-10.0.10
cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql  -DMYSQL_DATADIR=/data/mysql  -DSYSCONFDIR=/etc
make
make install
cd -

cd /usr/local/mysql
cp ./support-files/my-huge.cnf /etc/my.cnf
sed -i '/\[mysqld\]/ a\datadir = /data/mysq' /etc/my.cnf

./scripts/mysql_install_db --user=mysql

cp ./support-files/mysql.server /etc/rc.d/init.d/mysqld

chmod 0775 /etc/rc.d/init.d/mysqld

sed -i 's/^basedir=/basedir=\/usr\/local\/mysql/g' /etc/rc.d/init.d/mysqld
sed -i 's/^datadir=/datadir=\/data\/mysql/g' /etc/rc.d/init.d/mysqld

isSet=`grep "/usr/local/mysql/bin" /etc/profile | wc -l`
if [ "$isSet" != "1" ]; then
    echo "export PATH=$PATH:/usr/local/mysql/bin">>/etc/profile
fi

ln -s /usr/local/mysql/lib/mysql /usr/lib/mysql
ln -s /usr/local/mysql/include/mysql /usr/include/mysql

service mysqld start
chkconfig mysqld on

./bin/mysql_secure_installation
service mysqld restart
cd -

printf "\n========== MariaDB install Completed! ========\n\n"
printf "============== The End. ==============\n"